package com.ftg.learn.day10;

/**
 * 作业
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/8/8 下午2:05
 */
public class Homewor02 {

    // 1 : 多线程下面的题   厨子 (面包)  销售员.... (只能有一个面包)

    // 这个是一个共享变量 ，是否可能让其它线程看到
    private volatile boolean bread = false;

    private static int a = 0;

    public synchronized void createBread() {
        if(bread){
            //现在还有一个面包,不让厨师生产，等待
            try {
                //等待
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        if (!bread) {
            System.out.println( Homewor02.a++);
            bread = true;
            System.out.println(Thread.currentThread().getName()+"生产面包了");
            this.notifyAll();
        }
    }

    public synchronized void saleBread() {
        if(!bread){
            //现在还有一个面包,不让厨师生产，等待
            try {
                //等待
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (bread) {
            System.out.println( Homewor02.a++);
            bread = false;
            System.out.println(Thread.currentThread().getName()+"销售面包了");
            this.notifyAll();
        }
    }

    public static void main(String[] args) {
        Homewor02 homewor02 = new Homewor02();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                homewor02.createBread();
            }
        }, "厨子");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                homewor02.saleBread();
            }
        }, "销售员1");

        t1.start();

        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                homewor02.saleBread();
            }
        }, "销售员2");

        t2.start();
        t3.start();

    }

}
